<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 权限解析记录
 *
 * @icon fa fa-circle-o
 */
class Right extends Backend
{

    /**
     * Right模型对象
     * @var \app\admin\model\Right
     */
    protected $model = null;
    protected $noNeedLogin = ['add'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Right;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','target_name','own_name','createtime','updatetime']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $target_json = $params['target_text'];
            $own_json = $params['own_text'];
            unset($params['target_text']);
            unset($params['own_text']);
            Db::execute('TRUNCATE fa_tempright;');
            Db::execute('TRUNCATE fa_roleright;');
            // $result = $this->model->allowField(true)->save($params);
            $result = 1;
    
            if($result)
            {
                

                $lastId = $this->model->getLastInsID();
                //将json解析成数据
                $data = json_decode($target_json, true);
                if(isset($data))
                {
                    foreach ($data as &$item) {
                        // 保留需要的键，删除多余的键
                        $item = array_intersect_key($item, array_flip(['code', 'name']));
                        $item['right_id']=$lastId;
                        $item['type']=1;
                        if($this->is_english($item['code']))
                        {
                            if(preg_match('/\d+/',$item['code'],$arr)){
                                $no_code = $arr[0];
                                $en_head = str_replace($arr[0],'',$item['code']);
                                $item['en']=$en_head;
                                $item['code']=$no_code;
                                Db::name("Tempright")->insert($item);

                             }
                             else
                             {
                                $this->error("英文code解析错误");
                             }
                            
                        }
                        else
                        {
                           
                            $insert['tno_code']=$item['code'];
                            $insert['tno_codename']=$item['name'];
                            $insert['right_id']=$item['right_id'];
                            Db::name("Roleright")->insert($insert);
                            unset($insert);
                        }
                        
                    }
                }
               
                $tempright1 = Db::name('Tempright')->where(['right_id'=>$lastId,'type'=>1])->select(); //对标数据，先增加到表
                foreach ($tempright1 as $key => $value) {
                    $find = Db::name("Roleright")->where(['tno_code'=>$value['code'],'right_id'=>$value['right_id']])->find();
                    if($find)
                    {
                        $update['ten_code']=$find['ten_code'].'|'.$value['en'];
                       
                        Db::name("Roleright")->where(['tno_code'=>$value['code'],'right_id'=>$value['right_id']])->update($update);
                        unset($update);
                    }
                    else
                    {
                        $insert['tno_code']='';
                        $insert['tno_codename']=$value['name'];
                        $insert['ten_code']=$value['en'].$value['code'];
                        $insert['right_id']=$value['right_id'];
                        Db::name("Roleright")->insert($insert);
                        unset($insert);
                    }
                }



             
                //自己的权限
                $data2 = json_decode($own_json, true);
                if(isset($data2))
                {
                    foreach ($data2 as &$item) {
                        // 保留需要的键，删除多余的键
                        $item = array_intersect_key($item, array_flip(['code', 'name']));
                        $item['right_id']=$lastId;
                        $item['type']=2;
                        if($this->is_english($item['code']))
                        {
                            if(preg_match('/\d+/',$item['code'],$arr)){
                                $no_code = $arr[0];
                                $en_head = str_replace($arr[0],'',$item['code']);
                                $item['en']=$en_head;
                                $item['code']=$no_code;
                                //解析出来的带英文的权限，用数字去和对标的查询。

                                $find2 = Db::name("Roleright")->where(['tno_code'=>$item['code']])->find();
                                if($find2)
                                {
                                    //如果自己的权限（纯数字）和参考人权限一样，进行更新
                                    $update2['oen_code']=$find['oen_code'].'|'.$item['en'];
                                    Db::name("Roleright")->where(['right_id'=>$lastId,'tno_code'=>$item['code']])->update($update2);
                                    unset($update2);
                                }
                                else
                                {
                                    //如果自己的权限（纯数字）和参考人不一样，新增一行。
                                    $insert2['tno_code']='';
                                    $insert2['tno_codename']='';
                                    $insert2['ten_code']='';
                                    $insert2['ono_code']=$item['code'];
                                    $insert2['ono_codename']=$item['name'];
                                    $insert2['oen_code']=$item['en'];
                                    Db::name("Roleright")->insert($insert2);
                                }

                             }
                             else
                             {
                                $this->error("英文code解析错误");
                             }
                            
                        }
                        else
                        {
                            $find2 = Db::name("Roleright")->where(['tno_code'=>$item['code']])->find();
                            if($find2)
                            {
                                //如果自己的权限（纯数字）和参考人权限一样，进行更新
                                $update2['ono_code']=$item['code'];
                                $update2['ono_codename']=$item['name'];
                                Db::name("Roleright")->where(['right_id'=>$lastId,'tno_code'=>$item['code']])->update($update2);
                            }
                            else
                            {
                                //如果自己的权限（纯数字）和参考人不一样，新增一行。
                                $insert2['tno_code']='';
                                $insert2['tno_codename']='';
                                $insert2['ten_code']='';
                                $insert2['ono_code']=$item['code'];
                                $insert2['ono_codename']=$item['name'];
                                Db::name("Roleright")->insert($insert2);
                            }
                            
                            
                        }
                        
                    }
                }













                Db::commit();
            }
            else
            {
                Db::rollback();
                $this->error('系统错误');
            }





            
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


//将一维数组，拆分为包含字母和不包含的。
public function is_english($str) {
    $pattern = '/[a-zA-Z]/';
    return preg_match($pattern, $str);
}




}
